package com.bread.tliaswebmanagement.filter;

import com.bread.tliaswebmanagement.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
/*
@WebFilter(urlPatterns = "/*")
*/
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        if (requestURI.contains("/login")) {
            log.info("登录请求，放行");
            filterChain.doFilter(request, response); //放行
            return;
        }
        //不是登录请求，则要校验令牌
        //获取令牌
        String token = request.getHeader("token");
        if (token == null || token.isEmpty()) {
            log.info("令牌为空，未登录");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //令牌不为空，则要校验令牌
        try{
            JwtUtils.parseJwt(token);
        } catch (Exception e) {
            log.info("令牌非法");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        log.info("令牌合法");
        filterChain.doFilter(request, response);

    }
}
